using System;
using Castle.Core.Interceptor;
using log4net;

namespace Project.Library.Core.AOP
{
    /// <summary>
    /// Log the execution time of a method
    /// </summary>
    public class StatisticInterceptor : IInterceptor
    {
        #region IInterceptor Members

        public void Intercept(IInvocation invocation)
        {
            var logger = LogManager.GetLogger(invocation.TargetType);

            try
            {
                var startDate = DateTime.Now;

                invocation.Proceed();

                if (logger.IsDebugEnabled)
                {
                    var executionTime = DateTime.Now.Subtract(startDate).Seconds;
                    logger.Debug(
                        String.Format("The Method {0} took {1} seconds to execute",
                                      InterceptorHelper.GetMethodName(invocation),
                                      executionTime));
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw;
            }
        }

        #endregion
    }
}